using System;
using System.Collections.Generic;
using System.Windows.Forms;
using AssetManagementSystem.Model;
using AssetManagementSystem.Presenter;
using AssetManagementSystem.Utils;
using AssetManagementSystem.Utils.Events;
using AssetManagementSystem.View.IView;

namespace AssetManagementSystem.View.Controls {
    public partial class UILoanEditor : Form, ILoanView, IStudentView, IGroupView {

        Dictionary<string, Asset> assetList;
        Dictionary<string, Asset> selectedAssets;
        Dictionary<string, Group> groupList;
        Dictionary<string, Student> studentList;
        //==================================================
        // IGroupView Events
        //==================================================
        public event EventHandler Groups_LoadAll;
        public event EventHandler<SearchEventArgs> Groups_Find;
        public event EventHandler<GroupEventArgs> Group_Create;
        public event EventHandler<GroupEventArgs> Group_Update;
        public event EventHandler<GroupEventArgs> Group_Delete;
        public event EventHandler<GroupPropertiesEventArgs> GroupProperty_Delete;
        //==================================================

        //==================================================
        // IStudentView Events
        //==================================================
        public event EventHandler Students_LoadAll;
        public event EventHandler<SearchEventArgs> Students_Find;
        public event EventHandler<StudentEventArgs> Student_Create;
        public event EventHandler<StudentEventArgs> Student_Update;
        public event EventHandler<StudentEventArgs> Student_Delete;
        //==================================================

        //==================================================
        // ILoanView Events
        //==================================================
        public event EventHandler Loans_LoadAll;
        public event EventHandler<SearchEventArgs> Loans_Find;
        public event EventHandler<LoanEventArgs> Loan_Create;
        public event EventHandler<LoanEventArgs> Loan_Return;
        public event EventHandler<LoanAssetEventArgs> LoanAsset_Return;
        public event EventHandler LoanAssets_LoadAvailable;
        public event EventHandler<LoanEventArgs> Loan_Notify;
        //==================================================

        //Constructor for new asset
        public UILoanEditor() {
            InitializeComponent();
            studentList = new Dictionary<string, Student>();
            assetList = new Dictionary<string, Asset>();
            selectedAssets = new Dictionary<string, Asset>();
            groupList = new Dictionary<string, Group>();


            //Create a presenter to handle events and update display data
            StudentPresenter studentPresenter = new StudentPresenter(this);
            //fire event to request a list of all students
            this.Students_LoadAll.Invoke(this, new EventArgs());
            //Create loan presenter
            LoanPresenter loanPresenter = new LoanPresenter(this);
            //fire event to request a list of all loans
            this.Loans_LoadAll.Invoke(this, new EventArgs());
            //get available loan assets
            this.LoanAssets_LoadAvailable.Invoke(this, new EventArgs());
            //Create group presenter
            GroupPresenter groupPresenter = new GroupPresenter(this);
            //fire event to request a list of all group
            this.Groups_LoadAll.Invoke(this, new EventArgs());
        }

        //==================================================
        // IAssetView Methods
        //==================================================
        public void SetAvailableAssets(List<Asset> assets) {
            this.assetList.Clear();
            foreach (Asset asset in assets) {
                this.assetList.Add(asset.Id, asset);
            }
            RefreshAssetDisplay();
        }
        //==================================================

        //==================================================
        // IGroupView Methods
        //==================================================
        public void SetGroupList(List<Group> groups) {
            this.groupList.Clear();
            foreach (Group group in groups) {
                this.groupList.Add(group.Name, group);
            }
            RefreshGroupDisplay();
        }
        //==================================================

        //==================================================
        // IStudentView Methods
        //==================================================
        public void SetStudentList(List<Student> students) {
            this.studentList.Clear();
            foreach (Student student in students) {
                studentList.Add(student.StudentId, student);
            }
        }
        //==================================================

        //==================================================
        // ILoanView Methods
        //==================================================
        public void SetLoanList(List<Loan> loans) {
            //----
        }
        //==================================================

        //==================================================
        // Shared Interface Methods
        //==================================================
        public void ShowMessage(string message) {
            MessageBox.Show(message);
        }
        //==================================================

        //Setting Groups
        public void RefreshGroupDisplay() {
            ddGroups.Items.Clear();
            ddGroups.Items.Add(Group.ALL);
            foreach (KeyValuePair<string, Group> group in this.groupList) {
               ddGroups.Items.Add(group.Value.Name);
            }
            ddGroups.SelectedIndex = 0;
        }

        //display assets
        public void RefreshAssetDisplay() {
            //get the group to display - default all groups.
            string groupName = Group.ALL;
            if (ddGroups.SelectedIndex >= 0) {
                groupName = ddGroups.Items[ddGroups.SelectedIndex].ToString();
            }
            //display assets from the selected group
            gridAssets.Rows.Clear();
            foreach (KeyValuePair<string, Asset> asset in assetList) {
                if (groupName == Group.ALL || asset.Value.GroupName == groupName) {
                    gridAssets.Rows.Add(asset.Key, asset.Value.Name);
                }
            }

            //display selected assets
            gridLoanAssets.Rows.Clear();
            foreach (KeyValuePair<string, Asset> asset in selectedAssets) {
                gridLoanAssets.Rows.Add(asset.Key, asset.Value.Name);
            }
        }

        //Setting Students
        public void RefreshStudentDisplay() {
            //ddStudents.Items.Clear();
            //foreach (KeyValuePair<string, Student> student in this.studentList) {
            //    ddStudents.Items.Add(student.Key + ": " + student.Value.FirstName + " " + student.Value.LastName);
            //}
        }

        private void UIAssetEditor_Load(object sender, EventArgs e) {
            //set default due date to 1 week from current day
            dateDue.Value = DateTime.Now.AddDays(7);
            //set minimum due date to one millisecond in the future.
            dateDue.MinDate = DateTime.Now.AddDays(1);
        }

        public string TitleText {
            get { return lblTitle.Text; }
            set { setTitle(value); }
        }

        public void SetStudentId(string studentId) {
            txtStudentId.Text = studentId;
        }

        public void MoveAssetToLoanList(string assetId) {
            if (assetList.ContainsKey(assetId)) {
                Asset tmpAsset = assetList[assetId];
                selectedAssets.Add(assetId, tmpAsset);
                assetList.Remove(assetId);

                RefreshAssetDisplay();
            }
        }

        private void setTitle(string text) {
            lblTitle.Text = text;
            this.Text = text;
        }

        private void ddGroups_SelectedIndexChanged(object sender, EventArgs e) {
            RefreshAssetDisplay();
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e) {
            if (gridAssets.Rows.GetRowCount(DataGridViewElementStates.Selected) > 0) {
                string tmpKey = gridAssets.SelectedRows[0].Cells["AssetId"].Value.ToString();
                Asset tmpAsset = assetList[tmpKey];
                selectedAssets.Add(tmpKey, tmpAsset);
                assetList.Remove(tmpKey);

                RefreshAssetDisplay();
            }
        }

        private void btnRemove_Click(object sender, EventArgs e) {
            if (gridLoanAssets.Rows.GetRowCount(DataGridViewElementStates.Selected) > 0) {
                string tmpKey = gridLoanAssets.SelectedRows[0].Cells["SelAssetId"].Value.ToString();
                Asset tmpAsset = selectedAssets[tmpKey];
                assetList.Add(tmpKey, tmpAsset);
                selectedAssets.Remove(tmpKey);

                RefreshAssetDisplay();
            }
        }

        private void txtStudentId_TextChanged(object sender, EventArgs e) {
            if(studentList.ContainsKey(txtStudentId.Text)){
                txtStudentId.BackColor = System.Drawing.Color.PaleGreen;
            }else{
                txtStudentId.BackColor = System.Drawing.Color.MistyRose;
            }
        }

        private void btnSave_Click(object sender, EventArgs e) {
            if (!studentList.ContainsKey(txtStudentId.Text)) {
                MessageBox.Show("Please provide a valid student id for this loan");
            } else if (selectedAssets.Count < 1) {
                MessageBox.Show("Please add at least one asset to this loan before saving");
            } else {
                Loan loan = new Loan(DateTime.Now, dateDue.Value, txtStudentId.Text, new Dictionary<string,DateTime>());
                foreach(KeyValuePair<string, Asset> loanAsset in selectedAssets){
                    loan.Assets.Add(loanAsset.Key, DateTime.MinValue);
                }
                this.Loan_Create(this, new LoanEventArgs(loan));
                this.Close();
            }
        }
    }
}
